﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using monitor_2_DBwork;

namespace monitor_server_2_WPF
{
    /// <summary>
    /// Логика взаимодействия для UserControl1.xaml
    /// </summary>
    public partial class AccessListTabControl : Res.IControlForMainWindow
    {
        //private bool _visible;
        private bool _newUser;
        private ListSortDirection _sort = ListSortDirection.Ascending;

        private bool NewUser
        {
            set
            {
                _newUser = value;
                //var t = new TextBlock();
                //var image = new Image {Margin = new Thickness(0, 0, 5, 0), Stretch = Stretch.None};
                //var dp = new DockPanel();
                if (_newUser)
                {
                    AcceptButton.IsEnabled = false;
                    AddButton.IsEnabled = true;
                    //old
                    ModeTypeLabel.Content = Res.Rm.GetString("Addition");
                    DeleteButton.IsEnabled = false;

                    //t.Inlines.Add(Res.Rm.GetString("Add"));

                    //image.Source = Res.GetBitMapFromPng("accept_image_16");
                    //dp.Children.Add(image);
                    //dp.Children.Add(t);
                    //AcceptButton.Content = dp;
                }
                else
                {
                    AcceptButton.IsEnabled = true;
                    AddButton.IsEnabled = false;
                    //old
                    ModeTypeLabel.Content = Res.Rm.GetString("Modification");
                    DeleteButton.IsEnabled = true;
                    
                    //t.Inlines.Add(Res.Rm.GetString("Accept"));
                    
                    //image.Source = Res.GetBitMapFromPng("accept_image_16");

                    //dp.Children.Add(image);
                    //dp.Children.Add(t);
                    //AcceptButton.Content = dp;
                }
            }
            get { return _newUser; }
        }
        private readonly ObservableCollection<AccessData> _dataGridItems;

        class AccessData
        {
            public string Login { get; set; }
            public string Group { get; set; }
            public string Info { get; set; }
        }

        //private readonly TextBlock _itemHeader;

        public AccessListTabControl()
        {
            InitializeComponent();

            //Buttons add/accept
            var t1 = new TextBlock();
            var t2 = new TextBlock();
            var image1 = new Image { Margin = new Thickness(0, 0, 5, 0), Stretch = Stretch.None };
            var image2 = new Image { Margin = new Thickness(0, 0, 5, 0), Stretch = Stretch.None };
            var dp1 = new DockPanel();
            var dp2 = new DockPanel();
            //add
            t1.Inlines.Add(Res.Rm.GetString("Add"));
            image1.Source = Res.GetBitMapFromPng("accept_image_16");
            dp1.Children.Add(image1);
            dp1.Children.Add(t1);
            AddButton.Content = dp1;
            //accept
            t2.Inlines.Add(Res.Rm.GetString("Accept"));
            image2.Source = Res.GetBitMapFromPng("accept_image_16");
            dp2.Children.Add(image2);
            dp2.Children.Add(t2);
            AcceptButton.Content = dp2;

            Item1.Header = Res.Rm.GetString("AccessList");

            Item1.PreviewMouseDoubleClick += Item1_MouseDoubleClick;

            ControlsPanel.Background = new SolidColorBrush(Res.LighBlack);
            LoginLabel.Content = Res.Rm.GetString("Login");
            PasswordLabel.Content = Res.Rm.GetString("Password");
            AccessLabel.Content = Res.Rm.GetString("Access");
            InfoLabel.Content = Res.Rm.GetString("Info");
            ModeLabel.Content = Res.Rm.GetString("Mode") + ": ";
            NewUser = true;
            AccessBox.Items.Add(Res.Rm.GetString("Administrator"));
            AccessBox.Items.Add(Res.Rm.GetString("User"));

            CancelButton.Content = new Image { Source = Res.GetBitMapFromPng("cancel_image_16"),Stretch = Stretch.None};
            CancelButton.ToolTip = Res.Rm.GetString("Cancel");

            DeleteButton.Content = new Image { Source = Res.GetBitMapFromPng("delete_image_16"), Stretch = Stretch.None };
            DeleteButton.ToolTip = Res.Rm.GetString("Delete");

            var gc1 = new DataGridTextColumn
                {
                    Header = Res.Rm.GetString("UserName"),
                    Width = 155,
                    Binding = new Binding("Login")
                };
            var gc2 = new DataGridTextColumn
                {
                    Header = Res.Rm.GetString("Access"),
                    Width = 120,
                    Binding = new Binding("Group")
                };
            var gc3 = new DataGridTextColumn
                {
                    Header = Res.Rm.GetString("AdditionalInfo"),
                    Width = 220,
                    Binding = new Binding("Info")
                };
            DataG.Columns.Add(gc1);
            DataG.Columns.Add(gc2);
            DataG.Columns.Add(gc3);
            DataG.AutoGenerateColumns = false;
            _dataGridItems = new ObservableCollection<AccessData>();
            DataG.ItemsSource = _dataGridItems;
            DataG.CanUserAddRows = false;
            DataG.CanUserDeleteRows = false;
            DataG.IsReadOnly = true;
        }

        void Item1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if ((e.MouseDevice.DirectlyOver as TextBlock) == null ||
                (e.MouseDevice.DirectlyOver as TextBlock).Text != Res.Rm.GetString("AccessList"))
                return;
            ClearForm();
            Update();
        }

        public UIElement GetControl(out MainWindow.HidingDelegate del)
        {
            del = null;
            //del =  () =>
            //    {
            //        _visible = false;
            //    };
            //_visible = true;
            Update();
            ClearForm();
            return this;
        }

        public void Update()
        {
            string usersStr;
            try
            {
                usersStr = DBwork.GetUsers();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Res.Rm.GetString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (usersStr.Contains("err:"))
            {
                MessageBox.Show(usersStr.Substring(4), Res.Rm.GetString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            string[] split = usersStr.Split(';');
            _dataGridItems.Clear();
            foreach (string str in split)
            {
                if (str.Length < 1)
                    continue;
                string[] splitik = str.Split(':');
                _dataGridItems.Add(new AccessData {Login = splitik[0], Group = splitik[1], Info = splitik[2]});
            }
            DataG.Items.SortDescriptions.Clear();
            DataG.Items.SortDescriptions.Add(new SortDescription("Login", _sort));
            DataG.Columns[0].SortDirection = _sort;
            DataG.Columns[1].SortDirection = null;
            DataG.Columns[2].SortDirection = null;

        }

        private void LoginBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var str = DBwork.CheckUserExistance(((TextBox)sender).Text);
            if (str.Contains("err:"))
                return;
            NewUser = str == "0";
        }

        private void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            if (LoginBox.Text.Length < 1)
            {
                MessageBox.Show(Res.Rm.GetString("EnterUserName"));
                return;
            }
            if (PasswordBox.Text.Length < 1 && _newUser)
            {
                MessageBox.Show(Res.Rm.GetString("EnterPassword"));
                return;
            }
            if (AccessBox.SelectedIndex < 0)
            {
                MessageBox.Show(Res.Rm.GetString("ChooseAccess"));
                return;
            }
            string check;
            if (_newUser)
                check = DBwork.AddUser(LoginBox.Text, PasswordBox.Text, (AccessBox.SelectedIndex + 1).ToString(CultureInfo.InvariantCulture),
                                       InfoBox.Text);
            else if (PasswordBox.Text.Length < 1)
                check = DBwork.UpdateUserWithoutPassword(LoginBox.Text, LoginBox.Text, (AccessBox.SelectedIndex + 1).ToString(CultureInfo.InvariantCulture),
                                              InfoBox.Text);
            else
                check = DBwork.UpdateUser(LoginBox.Text, LoginBox.Text, PasswordBox.Text, (AccessBox.SelectedIndex + 1).ToString(CultureInfo.InvariantCulture),
                                          InfoBox.Text);
            if (check != "ok")
                MessageBox.Show(check.Contains("err:") ? check.Substring(4) : check, Res.Rm.GetString("Error"),
                                MessageBoxButton.OK,
                                MessageBoxImage.Warning);
            else
            {
                MessageBox.Show(Res.Rm.GetString("Complete"), Res.Rm.GetString("Complete"), MessageBoxButton.OK,
                                    MessageBoxImage.Information);
            }
            Update();
            ClearForm();
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (LoginBox.Text.Length < 1)
            {
                MessageBox.Show(Res.Rm.GetString("EnterUserName"));
                return;
            }
            var check = DBwork.DelUser(LoginBox.Text);
            if (check != "ok")
                MessageBox.Show(check.Contains("err:") ? check.Substring(4) : check, Res.Rm.GetString("Error"),
                                MessageBoxButton.OK,
                                MessageBoxImage.Warning);
            else
            {
                MessageBox.Show(Res.Rm.GetString("Complete"), Res.Rm.GetString("Complete"), MessageBoxButton.OK,
                                    MessageBoxImage.Information);
            }
            Update();
            ClearForm();
        }

        private void DataG_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            
            var dg = sender as DataGrid;
            if (dg == null)
                return;
            if(dg.SelectedCells.Count < 1)
                return;
            var item = dg.SelectedCells[0];
            if ((item.Column).DisplayIndex == 0)
            {
                var accessData = item.Item as AccessData;
                if (accessData != null) LoginBox.Text = accessData.Login;
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            ClearForm();
        }

        private void ClearForm()
        {
            LoginBox.Clear();
            PasswordBox.Clear();
            AccessBox.SelectedIndex = -1;
            InfoBox.Clear();
        }

        private void DataG_Sorting(object sender, DataGridSortingEventArgs e)
        {
            
            if(e.Column.DisplayIndex != 0)
                return;
            if(e.Column.SortDirection == null)
                return;
            _sort = e.Column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
            
        }


        
    }
}
